import os

pwd = os.getcwd()


DEVELOPER = os.popen("xcode-select -print-path").read().strip()
os.environ["DEVELOPER"] = DEVELOPER

DEST= os.path.join(pwd, "output")
os.environ["DEST"] = DEST

#ARCHS= "i386 x86_64 armv7 arm64".split()
ARCHS= "armv7 arm64".split()

#ARCHS= "armv7".split()

#LIBS="libopencore-amrnb.a libopencore-amrwb.a".split()
LIBS="libulua.a".split()

os.system("mkdir -p %s" % (DEST))

#os.system("./configure")


for arch in ARCHS:
	
	os.system("make clean")
	os.system("rm CMakeCache.txt")
	os.system("rm -rf CMakeFiles")

	IOSMV = "-miphoneos-version-min=7.0"
	os.environ["IOSMV"] = IOSMV
	oldPath = os.environ["PATH"]
	print "BuildArch", arch
	if arch == "armv7" or arch == "arm64":
		
		newPath = os.popen("xcodebuild -version -sdk iphoneos PlatformPath").read().strip()+"/Developer/usr/bin:"+oldPath
		os.environ["PATH"] = newPath
		print "####"
		print newPath

		SDK=os.popen("xcodebuild -version -sdk iphoneos Path").read().strip()
		os.environ["SDK"] = SDK
		os.environ["SDKROOT"] = SDK
		os.environ["sysroot"] = SDK
		print "####"
		print SDK

		CXX = "xcrun --sdk iphoneos clang++ -arch %s %s --sysroot=%s -isystem %s/usr/include" % (arch, IOSMV, SDK, SDK)
		os.environ["CXX"] = CXX
		print "####"
		print "CXX", CXX


		CC = "xcrun --sdk iphoneos clang -arch %s %s --sysroot=%s -isystem %s/usr/include" % (arch, IOSMV, SDK, SDK)
		os.environ["CC"] = CC
		print "####"
		print "CC", CC

		os.environ["ARCH"] = arch

		LDFLAGS="-Wl,-syslibroot,%s" % (SDK)
		os.environ["LDFLAGS"] = LDFLAGS
		print LDFLAGS

		#os.system("./configure --host=arm-apple-darwin --prefix=%s --disable-shared" % (DEST))
	else:

		newPath = os.popen("xcodebuild -version -sdk iphonesimulator PlatformPath").read().strip()+"/Developer/usr/bin:"+oldPath
		os.environ["PATH"] = newPath
		print newPath

		SDK=os.popen("xcodebuild -version -sdk iphonesimulator Path").read().strip()
		os.environ["SDK"] = SDK
		print SDK

		CXX = "xcrun --sdk iphoneos clang++ -arch %s %s --sysroot=%s -isystem %s/usr/include" % (arch, IOSMV, SDK, SDK)
		os.environ["CXX"] = CXX
		print CXX

		CC = "xcrun --sdk iphoneos clang++ -arch %s %s --sysroot=%s -isystem %s/usr/include" % (arch, IOSMV, SDK, SDK)
		os.environ["CC"] = CC
		print CC

		LDFLAGS="-Wl,-syslibroot,%s" % (SDK)
		os.environ["LDFLAGS"] = LDFLAGS
		print LDFLAGS

		#os.system("./configure --prefix=%s --disable-shared" % (DEST))

	os.system("cmake -DCMAKE_BUILD_TYPE:STRING=Debug CMakeLists.txt")

	os.system("make clean")
	os.system("make -j8")
	#os.system("make install")

	for i in LIBS:
		os.system("mv src/%s src/%s.%s" % (i, i, arch))

for i in LIBS:
	inp=""
	for arch in ARCHS:
		inp += " src/%s.%s " % (i, arch)
	
	cmd = "xcrun lipo -create -output %s/%s %s" % (DEST, i, inp)
	print cmd
	os.system(cmd)


		

			
